package com.franklin.ideaplugin.api.completion.json;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.franklin.ideaplugin.api.comment.PsiCommentResolverFactory;
import com.franklin.ideaplugin.api.ui.editor.CustomEditor;
import com.franklin.ideaplugin.api.utils.JsonPathUtils;
import com.franklin.ideaplugin.api.utils.PsiUtil;
import com.franklin.ideaplugin.easytesting.icon.PluginIcons;
import com.intellij.codeInsight.completion.CompletionContributor;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.psi.*;
import org.jetbrains.annotations.NotNull;

import java.awt.*;
import java.util.*;
import java.util.List;

/**
 * @author Ye Junhui
 * @since 2023/7/20
 */
public class EntityJsonCompletionContributor extends CompletionContributor {

    @Override
    public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
        Container parent = parameters.getEditor().getComponent().getParent();
        if (Objects.isNull(parent)) {
            return;
        }
        if (!(parent instanceof CustomEditor)) {
            return;
        }
        CustomEditor customEditor = (CustomEditor) parent;
        List<PsiUtil.FieldMethod> fieldMethodList = JsonPathUtils.resolveCurrentPathFields(parameters.getOriginalPosition(), customEditor);
        if (ArrayUtil.isEmpty(fieldMethodList)){
            return;
        }
        for (PsiUtil.FieldMethod fieldMethod : fieldMethodList) {
            LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(fieldMethod.getFieldName())
                    .withIcon(PluginIcons.PLUGIN_ICON)
                    .appendTailText(" " + buildTailText(fieldMethod),true)
                    .bold();
            result.addElement(lookupElementBuilder);
        }
    }

    /**
     * 注释
     * @param fieldMethod
     * @return
     */
    private String buildTailText(PsiUtil.FieldMethod fieldMethod){
        PsiField field = fieldMethod.getField();
        String tail = "";
        if (Objects.isNull(field)){
            return tail;
        }

        //注释
        String comment = PsiCommentResolverFactory.getInstance().resolveComment(field);
        if (StrUtil.isNotBlank(comment)){
            tail = tail + " " + comment;
        }

        //数据类型
        tail = tail + "  " + field.getType().getPresentableText();
        return tail;
    }

}
